package com.ktjy.controller;

import cn.max.anno.RequestMapping;
import com.ktjy.entity.AuctionUser;
import com.ktjy.service.AuctionUserService;
import com.ktjy.service.Impl.AuctionUserServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuctionUserControll {
    AuctionUserService auctionUserService = new AuctionUserServiceImpl();

    @RequestMapping("/register")
    public String registerAuctionuser(HttpServletRequest request, HttpServletResponse response) {
        String userIsAdmin = request.getParameter("userIsAdmin"); // 用户是否是管理员
        String username = request.getParameter("username"); // 用户名
        String password = request.getParameter("password");// 密码
        String idCard = request.getParameter("idCard");// 身份证
        String phone = request.getParameter("phone");// 手机
        String address = request.getParameter("address");// 地址
        String postcode = request.getParameter("postcode");// 邮编

        AuctionUser auctionUser = new AuctionUser();
        auctionUser.setUserName(username);
        auctionUser.setUserPassword(password);
        auctionUser.setUserCardNo(idCard);
        auctionUser.setUserTel(phone);
        auctionUser.setUserAddress(address);
        auctionUser.setUserPostNumber(postcode);
        auctionUser.setUserIsAdmin(userIsAdmin.equals("1") ? true : false);
        boolean a = auctionUserService.registerAuctionuser(auctionUser);
        if (a) {
            if (userIsAdmin.equals("1")) {
                //注册成功，跳转到管理员登录页面
                return "redirect:/login-admin.jsp";
            } else {
                return "redirect:/login.jsp";
            }
        } else {
            //注册失败，跳转到注册页面
            return "redirect:/register.jsp?userIsAdmin=" + userIsAdmin;
        }
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userIsAdmin = request.getParameter("userIsAdmin") != null ?
                request.getParameter("userIsAdmin") : "0"; //空值默认为0
        AuctionUser auctionUser = auctionUserService.login(username, password);

        if (auctionUser != null) {
            request.getSession().setAttribute("userIsAdmin", auctionUser.isUserIsAdmin() ? "1" : "0");
            //登录成功，跳转到管理员页面
            return "redirect:/do/getAuction";
        } else {
            //登录失败，跳转到登录页面
            return "redirect:/login.jsp?userIsAdmin=" + userIsAdmin;
        }
    }
}
